<template>
  <div>
    <h2>Vue - Vue - 学习</h2>
    <h2>{{ count1 }}</h2>
    <h2>人送外号--{{ city1 }}</h2>
    <hr />
    <h3>{{ count2 }}</h3>
    <h3>city2--{{ city2 }}</h3>
    <h2>message  -- {{message}}</h2>
    <h3></h3>
    <hr />
    <button @click="countAdd">count++</button>
    <button @click="countDel">count--</button>
    <h4>mapState---{{ count }}</h4>
    <h4>mapGetters---{{ newCount }}</h4>
    <h2>world---{{ world }}</h2>
    <input type="text" :value="world" @input="change" />
    <button @click="changeMessage('我不猜')">changeMessage{{message}}</button>
    <button @click="changeMessageAction('你不卷总有人卷，为什么你就不卷')">changeMessageAction</button>
  </div>
</template>


<script>
import store from "@/store";
import { mapGetters, mapMutations, mapState,mapActions } from "vuex";
export default {
  name: "vuex",
  data() {
    return {
      count1: this.$store.state.count,
      city1: this.$store.state.city,
    };
  },
  // 用这种方式获取可以通过state修改 上面的方法无法通过state修改
  // computed: {
  //     count2(){
  //         return this.$store.state.count
  //     },
  //     city2(){
  //         return this.$store.state.city
  //     },
  // },

  // 这是vue的辅助函数  上面的computed可以使用辅助函数简写成下面的代码
  computed: {
    ...mapState({
      count2: "count", //state=>state.count还可以继续简写成count 这是ES7语法
      // city2:state=>state.city
      city2: "city",
      world: "world",
    }),
    ...mapState([
      "count",
      'message', //this.count为store.state.count
    ]),
    ...mapGetters(["newCount"]), //this.newCount=store.getter.newCount
  },
  mounted() {
    console.log(store), console.log(this.$store);
  },
  methods: {
    // countAdd(){
    //     // 修改state 唯一方式 commit mutations
    //     this.$store.commit('countAdd')
    // },
    // countDel(){
    //     this.$store.commit('countDel')
    // },

    // 上面的都可以用vuex的辅助函数简写
    ...mapMutations([
      "countAdd", //将'this.countAdd()'映射为'this.$store.commit('countAdd')'
      "countDel",
      "changenworld",
    ]),
    change(e) {
      this.changenworld(e.target.value);
    },
    //         如何使用 actions

    // 子组件能通过 this.$store.dispatch 访问到

    // this.$store.dispatch('changetest'xxx)
    // 它会去把 changetest 分发到 actions 在通过 actions 提交到 mutation 执行
    changeMessageAction(a) {
        // dispatch(action) 发送action
      this.$store.dispatch("changeMessageAction", a);
    },
    changeMessage(msg){
      this.$store.commit("changeMsg",msg)
    },
    // computed: {
    //     ...mapState([
    //         'count'
    //     ])
    // }
  },
};
</script>